<?php
/**
 * Created by PhpStorm.
 * User: linyida
 * Date: 2019/7/27
 * Time: 上午10:57
 */
namespace App\Storage;

use EasySwoole\Component\Singleton;
use EasySwoole\Component\TableManager;
use EasySwoole\RedisPool\Redis;
use Swoole\Table;

class UserShopRelation {

    use Singleton;
    protected $table = 'user_shop_relation';

    function __construct()
    {
//        TableManager::getInstance()->add('userShopRelation',[
//            'fd' => ['type' => Table::TYPE_INT, 'size' => 8],
//            'shop_id' => ['type' => Table::TYPE_INT, 'size' => 8],
//            'shop_user_id' => ['type' => Table::TYPE_INT, 'size' => 8],
//            'shop_user_fd' => ['type' => Table::TYPE_INT, 'size' => 8],
//            'last_heartbeat' => ['type' => Table::TYPE_INT, 'size' => 4], //用户最后一次访问
//        ], 102400);
//
//        $this->table = TableManager::getInstance()->get('userShopRelation');
    }

    /**
     * 设置一条用户绑定关系信息。key 是userId，value是绑定关系
     * @param $userId
     * @param $fd
     * @param $shopId
     * @param $ShopUserId
     * @param $ShopUserFd
     * @return mixed
     */
    public function set($userId,$fd, $shopId, $ShopUserId, $ShopUserFd) {
        $data = [
            'fd'                => $fd,
            'shop_id'           => $shopId,
            'shop_user_id'      => $ShopUserId,
            'shop_user_fd'      => $ShopUserFd,
            'last_heartbeat'    => time(),
        ];
        $redis = Redis::getInstance()->pool('redis')::defer();
        return $redis->hSet($this->table,$userId,json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    /**
     * 获取一条用户绑定信息
     * @param $userId
     * @return array|mixed|null
     */
    function get($userId) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        $info = $redis->hGet($this->table,$userId);
        return isset($info) ? json_decode($info, true) : null;
    }

    /**
     * 删除一条用户绑定信息
     * @param $userId
     */
    function delete($userId) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        if ($redis->hExists($this->table,$userId)) {
            $redis->hDel($this->table,$userId);
        }
    }
}